
<!--上传文本组件组件 -->
<template>
  <div>
    <el-upload
      class="upload-demo"
      ref="upload"
      :action="serverUrl"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :auto-upload="false"
      list-type="text"
      :multiple="true"
      :on-error="uploadError"
      :http-request="uploadFile"

    >
      <el-button slot="trigger" size="small" type="primary">选取文本/种子</el-button>
<!--    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>-->
      <div slot="tip" class="el-upload__tip">只能上传文本/种子文件，且不超过500kb</div>
    </el-upload>
  </div>
</template>

<script>
  /**
   * 参考文件发送代码 https://www.jianshu.com/p/c662daa6bc77
   * 多文件上传代码 https://blog.csdn.net/weixin_43915587/article/details/91953230
   */
  import {ResultStatus} from "../views/constant/ResultStatus";
  import {StringUtil} from "../utils/StringUtil";

  export default {
    data() {
      return {
        imgUrl:'',//文件返回地址
        fileData: '',  // 文件上传数据（多文件合一）
        serverUrl: this.$axios.defaults.baseURL + '/file/upload',//文件上传地址
        fileList: [],
        //[{name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}, {name: 'food2.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}]

      };
    },
    methods: {
      submitUpload:async function() {


          this.fileData = new FormData();  // new formData对象
          this.$refs.upload.submit();  // 提交调用uploadFile函数

          let config = {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          };

          var self = this;
        await  this.$axios.post(this.serverUrl, this.fileData, config).then(
            (response) => {
              let datas = response.data;
              if (datas.code != ResultStatus.SUCCESS) {
                StringUtil.warning(datas.message);
                return;
              }
              this.imgUrl = datas.data;
              StringUtil.checkNull(this.imgUrl);


            }
          ).catch(function (error) {
            StringUtil.warning(error.data.data);
          })
          console.log(this.imgUrl)
          this.$emit('func', this.imgUrl)

        },
      handleRemove(file, fileList) {
        console.log(file, fileList);
      },
      handlePreview(file) {
        console.log(file);
      },

      // 富文本图片上传失败
      uploadError() {
        // loading动画消失
        this.$message.error("图片插入失败");
      },
      // 上传文件
      uploadFile(file) {
        this.fileData.append('files', file.file);  // append增加数据
      },
    }
  }
</script>
